from day20.models.models_stu import Stu
from day20.models.models_score import Score
from day20.models.models_emp import Emp
from fastapi import FastAPI,Depends,HTTPException, APIRouter
from sqlalchemy.orm import Session
import uvicorn
from typing import List
from day20.database.database import get_db
from day20.schema.schema_stu import StuCreateSchema, StuUpdateSchema, StuResponseSchema
from day20.database.database import Base, engine
from day20.crud.crud_stu import *

#创建一个fastapi的应用实力
stu_app=APIRouter()

#创建数据库表
# Base.metadata.create_all(bind=engine)

#创建添加学生信息
@stu_app.post('/stu/create',response_model=StuCreateSchema, summary="添加学生信息")
def create_stu(stu_schema:StuCreateSchema,db:Session=Depends(get_db)):
    db_stu_schema=stu_get_id(db,id=stu_schema.stu_id)
    if  db_stu_schema:
        raise  HTTPException(status_code=404, detail="学生已存在")
    return stu_create(db,stu_schema=stu_schema)

# 查所有学生信息
@stu_app.get('/stu/getall', summary="查询所有学生信息")
async def get_stu_all(db: Session=Depends(get_db)):
    return stu_get_all(db=db)

#查询学生信息（按学生编号查询）
@stu_app.get('/stu/get_id',response_model=StuCreateSchema, summary="按学号查询学生信息")
async def get_stu_id(stu_id:int,db:Session=Depends(get_db)):
    db_stu_schema=stu_get_id(db,id=stu_id)
    if not db_stu_schema:
        raise HTTPException(status_code=404, detail="学生不存在")
    return stu_get_id(db,id=stu_id)

#查询学生信息（按学生姓名查询）
@stu_app.get('/stu/get_name',response_model=List[StuCreateSchema], summary="按姓名查询学生信息")
async def get_stu_name(stu_name:str,db:Session=Depends(get_db)):
    db_stu_schema = stu_get_name(db, name=stu_name)
    if not db_stu_schema:
        raise HTTPException(status_code=404, detail="学生不存在")
    return stu_get_name(db, name=stu_name)

#查询学生信息（按学生班级查询）
@stu_app.get('/stu/get_class',response_model=list[StuCreateSchema], summary="按班级查询学生信息")
async def get_stu_class(stu_class:str,db:Session=Depends(get_db)):
    db_stu_schema=stu_get_class(db,Class=stu_class)
    if not db_stu_schema:
        raise HTTPException(status_code=404, detail="班级不存在")
    return stu_get_class(db,Class=stu_class)

# 更新学生信息
@stu_app.post('/stu/update/{stu_id}',response_model=StuResponseSchema, summary="更新学生信息")
def upddate_stu(stu_id:int,stu_updated:StuUpdateSchema,db:Session=Depends(get_db)):
    return  stu_update(db,stu_id,stu_updated)


# if __name__ == '__main__':
#     uvicorn.run("stus:stu_app", host="localhost", port=8009, reload=True)